<template>
  <!-- 全局后台任务指示器 - 右侧边栏样式 -->
  <transition name="slide-fade">
    <div 
      v-if="hasRunningTasks"
      class="global-background-tasks"
      :class="{ collapsed: !isExpanded }"
      :title="isExpanded ? '单击收起，双击查看详情' : '单击展开'"
    >
      <!-- 收起状态：只显示箭头 -->
      <div 
        v-if="!isExpanded" 
        class="arrow-icon"
        @click="isExpanded = true"
      >
        <el-icon><DArrowLeft /></el-icon>
      </div>
      
      <!-- 展开状态：显示完整内容 -->
      <div 
        v-else
        class="task-content-wrapper"
        @click="handleSingleClick"
        @dblclick="handleDoubleClick"
      >
        <div class="task-icon">
          <el-icon v-if="firstTask.completed" class="icon-success"><CircleCheck /></el-icon>
          <el-icon v-else class="icon-loading"><Loading /></el-icon>
        </div>
        <div class="task-text">
          <div class="task-label">{{ firstTask.completed ? '已完成' : '进行中' }}</div>
          <div class="task-progress">{{ firstTask.progress.current }}/{{ firstTask.progress.total }}</div>
        </div>
        <div v-if="runningTasks.length > 1" class="task-badge">
          +{{ runningTasks.length - 1 }}
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { CircleCheck, Loading, DArrowLeft } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import { useBackgroundTaskStore } from '@/stores/backgroundTask'
import { useRouter } from 'vue-router'

const backgroundTaskStore = useBackgroundTaskStore()
const router = useRouter()

// 展开/收起状态
const isExpanded = ref(true)

// 单击/双击处理
const clickTimer = ref(null)

// 当前时间戳（用于触发 computed 重新计算）
const currentTime = ref(Date.now())

// 定时更新当前时间
let timer = null
onMounted(() => {
  timer = setInterval(() => {
    currentTime.value = Date.now()
  }, 1000) // 每秒更新一次
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

// 运行中的任务
const runningTasks = computed(() => {
  // 使用 currentTime.value 来触发重新计算
  const now = currentTime.value
  return backgroundTaskStore.tasks.filter(t => !t.completed || now - t.endTime < 5000)
})

// 是否有运行中的任务
const hasRunningTasks = computed(() => {
  return runningTasks.value.length > 0
})

// 第一个任务（主要显示的任务）
const firstTask = computed(() => {
  return runningTasks.value[0] || {}
})

// 获取任务类型名称
const getTaskTypeName = (type) => {
  const names = {
    'jar-upload': 'JAR上传',
    'job-operation': '作业操作'
  }
  return names[type] || '任务'
}

// 处理单击事件（延迟执行，给双击留时间）
const handleSingleClick = () => {
  // 清除之前的定时器
  if (clickTimer.value) {
    clearTimeout(clickTimer.value)
  }
  
  // 延迟300ms执行收起操作
  clickTimer.value = setTimeout(() => {
    isExpanded.value = false
    clickTimer.value = null
  }, 300)
}

// 处理双击事件
const handleDoubleClick = () => {
  // 取消单击的延迟执行
  if (clickTimer.value) {
    clearTimeout(clickTimer.value)
    clickTimer.value = null
  }
  
  // 立即跳转到任务页面
  showTaskDetail(firstTask.value)
}

// 显示任务详情
const showTaskDetail = (task) => {
  // 跳转到对应页面
  if (task.type === 'jar-upload') {
    router.push('/jars')
  } else if (task.type === 'job-operation') {
    router.push('/jobs')
  }
}

// 取消任务
const cancelTask = async (taskId) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消此任务吗？',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await backgroundTaskStore.cancelTask(taskId)
  } catch (error) {
    // 用户取消
  }
}
</script>

<style scoped>
/* 全局后台任务指示器 - 右侧边栏样式 */
.global-background-tasks {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  z-index: 2000;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px 12px;
  background: linear-gradient(180deg, rgba(255, 152, 0, 0.95) 0%, rgba(255, 193, 7, 0.95) 100%);
  border-radius: 8px 0 0 8px;
  box-shadow: -4px 0 16px rgba(255, 152, 0, 0.4);
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 60px;
  overflow: hidden;
}

.global-background-tasks:hover {
  box-shadow: -6px 0 20px rgba(255, 152, 0, 0.6);
  transform: translateY(-50%) translateX(-4px);
}

/* 收起状态 */
.global-background-tasks.collapsed {
  min-width: 32px;
  padding: 12px 8px;
}

.global-background-tasks.collapsed:hover {
  transform: translateY(-50%) translateX(-6px);
}

/* 箭头图标 */
.arrow-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  animation: pulse-arrow 2s ease-in-out infinite;
  cursor: pointer;
}

@keyframes pulse-arrow {
  0%, 100% { 
    opacity: 1;
    transform: translateX(0);
  }
  50% { 
    opacity: 0.7;
    transform: translateX(-3px);
  }
}

/* 展开内容包装器 */
.task-content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  position: relative;
}

.task-icon {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.25);
  color: white;
  font-size: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.icon-success {
  animation: pulse 2s ease-in-out infinite;
}

.icon-loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

.task-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  writing-mode: vertical-rl;
  text-orientation: upright;
}

.task-label {
  font-size: 12px;
  font-weight: 600;
  color: white;
  letter-spacing: 2px;
  line-height: 1;
}

.task-progress {
  font-size: 11px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.9);
  letter-spacing: 1px;
  line-height: 1;
}

.task-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  color: #ff9800;
  font-size: 11px;
  font-weight: 700;
  border-radius: 50%;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}

/* 滑动淡入淡出动画 */
.slide-fade-enter-active {
  transition: all 0.4s ease;
}

.slide-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-fade-enter-from {
  opacity: 0;
  transform: translateY(-50%) translateX(100%);
}

.slide-fade-leave-to {
  opacity: 0;
  transform: translateY(-50%) translateX(100%);
}
</style>

